<script lang="ts" >
import { defineComponent, ref ,onMounted} from 'vue';

export default defineComponent({
  name: 'Home',
  setup()
  {
    const messages = ref<string[]>([])as any;
    const prompt = ref('你是谁？');
    ref<string>('');
    const send = async () => {
      if (prompt.value.trim()) {
        messages.value.push({prompt: prompt.value });
        const response = await query(prompt.value);
        prompt.value = '';
        messages.value.push({response: response});
      }
    };

    const query = async (prompt: string) => {
      try {
        const response = await fetch('http://127.0.0.1:1234/', { // 指定主机名和端口号
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ prompt }),
        });
        const data = await response.json();
        scrollToBottom();
        return data.response
      } catch (error) {
        return '无法链接到服务'+error;
      }
    };
    const scrollToBottom =(elementId="chat") => {
      var element = document.getElementById(elementId);
      if (element) {
        element.scrollTop = element.scrollHeight; // 滚动到底部
      }
    }
    onMounted(() => {
      send()
    });
    return {
      messages,
      prompt,
      send,
    };

  }

})
</script>
<template>
  <el-card  style="width: 1200px;margin: 0 auto;height: 895px" >
    <div id="chat" style="height: 730px;overflow-y:auto;">
      <div v-for="message in messages" >
        <div style="text-align: right">
          <el-text  size="large">{{ message.prompt }}</el-text>
        </div>
        <div style="text-align: left">
          <el-text  size="large"><pre>{{ message.response }}</pre></el-text>
        </div>
      </div>
    </div>
    <template #footer>
      <el-input
          id="input"
          v-model="prompt"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea">
        <template #suffix>
          <el-button type="primary" @click="send">发送</el-button>
        </template>
      </el-input>
    </template>
  </el-card>
</template>
<style scoped>
/* 隐藏所有浏览器中的滚动条 */
#chat ,#input{
  /* 禁用滚动条，但允许内容滚动 */
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
}
#chat::-webkit-scrollbar ,#input::-webkit-scrollbar {
  display: none;  /* Chrome, Safari and Opera */
}

/* 同时确保内容可以在容器内滚动 */
#chat ,#input {
  overflow-y: scroll; /* 或者 'auto'，根据需求选择 */
}
pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-family: monospace; /* 确保文本以等宽字体显示 */
}


</style>